package cn.bestick.thirteenKiller.dao;

import cn.bestick.thirteenKiller.dmo.CardImage;
import cn.bestick.thirteenKiller.util.MD5;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by bestick on 2016/1/17.
 */
public class DataBase extends BaseDao implements Data {

    private Connection con;
    private static DataBase db;

    private DataBase() {
    }

    public static DataBase getInstance() {
        return db == null ? db = new DataBase() : db;
    }

//  public static void main(String[] args) {
//      getInstance().saveData("tmp");
//  }

    @Override
    public void saveData(String path) {
        con = this.getCon();
        File[] files = new File(path).listFiles((dir, name) -> {
            return name.endsWith(".jpg");
        });
        try {
            for (int i = 0; i < files.length; i++) {
                FileInputStream fileImage = new FileInputStream(files[i]);
                ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
                byte[] buffer = new byte[(int) files[i].length()];
                while (fileImage.read(buffer) != -1) {
                    byteArray.write(buffer, 0, buffer.length);
                }
                String sql = "insert into t_tmp(imageName,imageData,imageSize,MD5) values(?,?,?,?)";
                PreparedStatement insertStm = con.prepareStatement(sql);
                insertStm.setString(1, files[i].getName());
                insertStm.setBytes(2, byteArray.toByteArray());
                insertStm.setInt(3, (int) files[i].length());
                insertStm.setString(4, MD5.fileMD5(files[i].getPath()));
                insertStm.execute();
                fileImage.close();
                byteArray.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close(con);
        }
    }

    /**
     * 根据sql获取List<CardImage>
     *
     * @param sql
     * @return
     */
    private List<CardImage> getCardImgList(String sql) {
        con = this.getCon();
        List<CardImage> cardImgList = new ArrayList();
        CardImage cardImage;
        try {
            PreparedStatement pstmt = con.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery(sql);
            while (rs.next()) {
                cardImage = new CardImage();
                cardImage.setImageName(rs.getString("imageName"));
                cardImage.setImageData(rs.getBytes("imageData"));
                cardImage.setImageSize(rs.getInt("imageSize"));
                cardImage.setMD5(rs.getString("MD5"));
                cardImgList.add(cardImage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close(con);
        }
        return cardImgList;
    }

    @Override
    public List<CardImage> getWantedCardImgList() {
        String sql = "select * from t_total where MD5 not in (select MD5 from t_tmp)";
        return this.getCardImgList(sql);
    }

    @Override
    public List<CardImage> getTotalCardImgList() {
        String sql = "select * from t_total";
        return this.getCardImgList(sql);
    }

    @Override
    public void truncateTmp() {
        con = this.getCon();
        try {
            String sql = "truncate table t_tmp";
            PreparedStatement pstmt = con.prepareStatement(sql);
            pstmt.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close(con);
        }
    }

    /**
     * 获取图片数据
     * @return List<byte[]>
     */
    public List<byte[]> getImgData() {
        List<byte[]> imgData = new ArrayList<>();
        List<CardImage> cardImgList = db.getWantedCardImgList();
        cardImgList.forEach(
                (card) -> imgData.add(card.getImageData())
        );
        return imgData;
    }
}
